package com.robot.web;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.robot.dto.UserDTO;
import com.robot.service.UserService;
import com.robot.web.util.CredentialsHelperUtil;

public class RegistrationController {

	private UserDTO newUser;
	@Autowired
	UserService userService;

	public RegistrationController() {
		System.out
				.println("se instancia objeto de la clase RegistrationController");
		this.newUser = new UserDTO();
	}

	public void saveNewUser() {

		System.out.println("Guardando nuevo usuario ");
		System.out.println(newUser.getFirstLastName());

		// Encriptamos la contraseña
		String passwordHash = CredentialsHelperUtil.calculateHash(
				this.newUser.getPassword(), this.newUser.getPassword());
		// Cambiamos por la contrseña encriptada
		this.newUser.setPassword(passwordHash);
		UserDTO usuarioNuevo = userService.saveUser(this.newUser);

		// Con esto enviamos a una pagina de confirmacion si todo es correcto
		RequestContext context = RequestContext.getCurrentInstance();

		if (usuarioNuevo != null) {
			context.addCallbackParam("view", "creacion_exitosa.xhtml");
		}

	}

	public void finalizar() {
		// se clarea los datos de la interfaz
		System.out.println("finalizar   --- [ok]");
		this.newUser = new UserDTO();
	}

	public UserDTO getNewUser() {
		return newUser;
	}

	public void setNewUser(UserDTO newUser) {
		this.newUser = newUser;
	}
}
